﻿using System;
using System.Collections.Generic;

using Builderator.Core.Plugin;
using Builderator.Core.Trigger;
using Builderator.Core.Interfaces;

namespace Builderator.Core.Action
{
    public class IntegrationTrigger : TriggerBase, ITrigger, IDependency
    {
        [DocumentProperty("Interval", typeof(int), false)]
        public int Interval
        {
            get;
            set;
        }

        public List<IAction> SourceActions
        {
            get;
            set;
        }

        public IntervalTimer Timer
        {
            get;
            set;
        }

        private Dictionary<Guid, int> RevisionDict
        {
            get;
            set;
        }

        public IntegrationTrigger()
            : base("Integration", new Guid("8967D2E6-FB6D-11E0-854C-50034824019B"))
        {
              
        }

        public override void Start()
        {
            this.RevisionDict = new Dictionary<Guid, int>();

            if (this.Interval == 0)
                return;

            int revision = 0;

            this.DebugMessage(string.Format("Integration trigger looking at {0} source actions", this.SourceActions.Count));

            if (this.SourceActions != null)
            {
                foreach (ISource source in this.SourceActions)
                {
                    this.DebugMessage(source.Name);

                    revision = source.GetRevision();

                    this.DebugMessage(string.Format("Source {0} at revision {1}", source.Name, revision));

                    this.RevisionDict.Add(source.Identifier, source.GetRevision());
                }
            }

            this.DebugMessage(string.Format("Setting time interval to {0} seconds", this.Interval * 1000));

            this.Timer = new IntervalTimer(this.Interval * 1000, new IntervalTimer.Trigger(this.TriggerCheck));

            this.Timer.Start();
        }

        private void TriggerCheck()
        {
            int revision;

            foreach (ISource source in this.SourceActions)
            {
                revision = source.GetRevision();

                this.DebugMessage(string.Format("Source {0} at revision {1}", source.Name, revision));

                if (revision > this.RevisionDict[source.Identifier])
                {
                    this.DebugMessage(string.Format("Source {0} updating revision {1} to {2} and triggering build {3}", source.Name, this.RevisionDict[source.Identifier], revision, this.Associated));

                    this.RevisionDict[source.Identifier] = revision;

                    this.TriggerBuild();
                }
            }

            this.Timer.Restart();
        }

        public override void Stop()
        {
            this.Timer.Stop();
        }
    }
}